(function($) {
	var methods = {
			"init": function(options){
				$.extend( $.madminpi.global, options );
				return this.each(function(){
					$.madminpi.create();
				});
			}
		};

	$.madminpi = {};
	
	$.madminpi.global = {
		//global variables
		"menuDiv":null
	};
	
	$.fn.marcAdmin = function( method ) {	    
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.dialogPrompt' );
		}
	};
	
	$.madminpi.create = function()
	{
		//build out admin menu
		var _appBody = $('#appBody');
		
		_appBody.append(
			$('<ul/>')
				.append($('<li/>')
					.append($('<a/>')
						.attr('href','#tabHome')
						.text('Home')
					)
				)
				.append($('<li/>')
						.append($('<a/>')
							.attr('href','#tabPeople')
							.text('People')
						)
				)
				.append($('<li/>')
						.append($('<a/>')
							.attr('href','#tabMeetings')
							.text('Meetings')
						)
				)
				.append($('<li/>')
					.append($('<a/>')
						.attr('href','#tabReports')
						.text('Reports')
					)
				)
			)
			.append($('<div/>')
				.attr('id','tabHome')
			)
			.append($('<div/>')
					.attr('id','tabPeople')
			)
			.append($('<div/>')
				.attr('id','tabMeetings')
			)
			.append($('<div/>')
				.attr('id','tabReports')
			);
		
		$.madminpi.buildHomeTab();
		$.madminpi.buildPeopleTab();
		$.madminpi.buildMeetingTab();
		$.madminpi.buildReportsTab();
		
		$('#appBody').tabs();
	};
	
	$.madminpi.buildHomeTab = function()
	{
		_containingDiv = $('#tabHome');
		
		var _homeMenu = 
				$('<ul/>')
					.attr('id','homeMenu')
					.append($('<li/>')
						.attr('id','menuAtAGlance')
						.append($('<a/>')
							.attr('href','#')
							.text('At A Glance')
						)
					)
					.append($('<li/>')
						.attr('id','menuNewMeeting')
						.append($('<a/>')
							.attr('href','#')
							.text('New Meeting')
						)
					)
					.append($('<li/>')
						.attr('id','menuNewStudent')
						.append($('<a/>')
							.attr('href','#')
							.text('New Student')
						)
					)
					.append($('<li/>')
						.attr('id','menuContactPeople')
						.append($('<a/>')
							.attr('href','#')
							.text('Contact People')
						)
					)
					
					.append($('<li/>')
						.attr('id','menuPeopleSearch')
						.append($('<a/>')
							.attr('href','#')
							.text('People Search')
						)
					)
					.append($('<li/>')
						.attr('id','menuApprovals')
						.append($('<a/>')
							.attr('href','#')
							.text('Approvals')
					)
				);
		
		_homeMenu.menu();
		_containingDiv.append(
			$('<table/>')
				.attr({
					'id':'homeTable',
					'border': 1,
					'width': '100%'
				})
				.css('height','100%')
				.append($('<tr>')
					.append($('<td>')
						.attr({
							id: 'TableMenuSide',
							valign: 'top'
						})
						.append(_homeMenu)
					)
					.append($('<td>')
						.attr({
							id: 'TableBodySide',
							width: '80%'
						})
					)
				)
		);
		
		$('#menuAtAGlance').click(function()
		{
			$('#homeBody').remove();
			$('#TableBodySide')
				.append(
					$('<div/>')
						.attr('id','homeBody')
				);
			$.ajax({ 
		  	  	url:"/marc/ReportDataService",
		  	  	data:{"ReportType":"attendanceBasic"},
				type:'POST',
				dataType:"json",
				success: function(html){
					makeGraph(html['Meetings']);
				},
				error: function(html){
					alert("An error occured while gathering Report data." +
							"\nPlease refresh your browser and try again." +
							"\n\nIf problem persists please contact BigHelp Ministries.");
				}
			}); //Closes AJAX
			
	        function makeGraph(mtgData)
	        {
	        	var _categoryArray = [];
	            var _data = [];
	            var length = mtgData.length;
	            
	            for (var i = 0; i < length; i++) {
	            	_categoryArray[i] = mtgData[i]['Start Date'];
	            	_data[i] = mtgData[i]['Attendees'];
	            };
	    
	            var chart = new Highcharts.Chart({
            		chart: {
                        renderTo: 'homeBody',
                        type: 'line',
                        marginRight: 130,
                        marginBottom: 25
                    },
                    exporting: {
                    	enabled: false
                    },
                    credits: {
                    	enabled: false
                    },
                    title: {
                        text: 'LifeNight Meeting Attendance',
                        x: -20 //center
                    },
                    subtitle: {
                        text: 'Last 10 LifeNights',
                        x: -20
                    },
                    xAxis: {
                        categories: _categoryArray
                    },
                    yAxis: {
                        title: {
                            text: 'Students'
                        },
                        tickInterval: 5,
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#808080'
                        }]
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -10,
                        y: 50,
                        borderWidth: 0
                    },
                    series: [{
                    	name: 'Attendance',
                    	data: _data
                    }]
	            });
	        };
		});
		
		$('#menuNewMeeting').click(function()
		{
			$('#homeBody').remove();
			$('#TableBodySide')
			.append($('<div/>').attr({'id':'homeBody','align':'center'}));
			
			$.ajax({ 
		  	  	url:"/marc/MeetingSigninService",
		  	  	data:{"RequestType":"CheckForOpenMeetings"},
				type:'POST',
				dataType:"json",
				success: function(html)
				{
					var _meetingIDs = html['MeetingIDs'];
					var _meetingTypes = html['MeetingTypes'];
					
					if(_meetingIDs.length == 1)
					{
						$('#homeBody').append(
							$('<div>')
								.attr('id','mtgActiveDialog')
								.append($('<center>')
									.append($('<img>').attr('src','img/alert.png').css('height','50px'))
									.append($('<br>'))
									.append("A " + _meetingTypes[0] + " meeting is already active.")
								)
						);
						$('#mtgActiveDialog').dialog({
							buttons: {
								'Join Active Meeting': function()
								{
									window.location = "meeting.jsp";
								}, 
								'New': function()
								{
									$('#mtgActiveDialog').dialog('close');
									$('#mtgActiveDialog').remove();
									displayNewMeetingForm();
								}
							}
						});
						$('#mtgActiveDialog').dialog( "option", "width", '75%' );
						$('#mtgActiveDialog').dialog( "option", "position", 'center' );
					}
					else if(_meetingIDs.length > 1)
					{
						alert("Multiple meetings currently active!");
					}
					else
					{
						displayNewMeetingForm();
					}
				},
				error: function(html){
					alert("An error occured while gathering Report data." +
							"\nPlease refresh your browser and try again." +
							"\n\nIf problem persists please contact BigHelp Ministries.");
				}
			}); //Closes AJAX
			
			function displayNewMeetingForm()
			{
				$('#homeBody')
				.append(
					$('<form>')
						.attr('id','newMtgForm')
						.append(
							$('<img>')
								.attr({
									'src':'img/Meeting.jpg',
									'height':'100px'
								})
						)
						.append(
							$('<h2>')
							.text('New Meeting')
						)
				);
	
				var _currDate = new Date();
				var _today = (_currDate.getFullYear() + "-" + (_currDate.getMonth()+1) + "-" + _currDate.getDate());
				$.ajax({ 
			  	  	url:"/marc/MeetingSigninService",
			  	  	data:{"RequestType":"meetingTypes"},
					type:'POST',
					dataType:"json",
					success: function(html)
					{
						$('#newMtgForm').append(
							$('<h4>')
								.attr('id','mtgTypeHeader')
								.text('Meeting Type: ')
								.append(
									$('<select>')
										.attr('id','meetingType')
								)
							)
							.append(
								$('<h4>')
									.attr('id','startDateHeader')
									.append('Meeting Start: \t\t\t')
									.append($('<input>')
										.attr({
											'type':'text',
											'id':'startDate'
										})
									)
							)
							.append(
								$('<h4>')
									.attr('id','attendantModeHeader')
									.text('Use Attendant Mode: ')
									.append(
										$('<input>')
											.attr({
												'id':'attendantMode',
												'type':'checkbox',
												'checked':'checked'
											})
									)
							)
							.append(
									$('<input>')
									.attr({
										'type':'submit',
										'id':'newMtgFormSubmitButton',
										'value':'Start!'
									})
							);
						
						$('#startDate').datepicker({ dateFormat: "yy-mm-dd" }).show();
						$('#startDate').datepicker('setDate',new Date());
						//$('#startDate').append($('<input>').attr({'id':'startTime', 'value':''}));
			
						var types = html['MeetingTypes'];
						var typeIDs = html['MeetingTypeIDs'];
						
						for(var i=0; i<types.length; i++)
						{
							var thisID = typeIDs[i];
							var thisType = types[i];
							$('#meetingType')
								.append(
									$('<option>')
										.attr({
											'id':thisID,
											'value':thisType
										})
										.text(thisType)
							);
						};
					},
					error: function(html){
						alert("An error occured while gathering Meeting types." +
								"\nPlease refresh your browser and try again." +
								"\n\nIf problem persists please contact BigHelp Ministries.");
					}
				}); //Closes AJAX
				
				$('#newMtgForm').submit(function(e)
				{
					var _startDate = $('#startDate').val();
					var _typeID = $('#meetingType').children(":selected").attr("id");
					var _attendantMode;
					
					if($('#attendantMode').is(':checked'))
					{
						_attendantMode = 1;
					}
					else
					{
						_attendantMode = 0;
					}
					
			
					e.preventDefault();
			
					$.ajax({ 
				  	  	url:"/marc/MeetingSigninService",
				  	  	data:{
				  	  		"RequestType":"startNewMeeting",
				  	  		"MeetingType":_typeID,
				  	  		"UserId":$('#globalSettings').data('userData')['UserId'],
				  	  		"StartDate":_startDate,
				  	  		"AttendantMode": _attendantMode
				  	  		},
						type:'POST',
						dataType:"json",
						success: function(html)
						{
							var _mtgID = html['MeetingID'];
							alert("Meeting #" + _mtgID + " started successfully!");
							window.location = 'meeting.jsp';
						},
						error: function(html){
							alert("An error occured while gathering Report data." +
									"\nPlease refresh your browser and try again." +
									"\n\nIf problem persists please contact BigHelp Ministries.");
						}
					}); //Closes AJAX
				});
			}
		});
		
		$('#menuNewStudent').click(function()
		{
			alert('Clicked New Student!');
		});
		$('#menuContactPeople').click(function()
		{
			alert('Clicked Contact People!');
		});
		$('#menuPeopleSearch').click(function()
		{
			alert('Clicked People Search!');
		});
		$('#menuApprovals').click(function()
		{
			alert('Clicked Approvals!');
		});
		
		$('#menuAtAGlance').click();
	};
	
	$.madminpi.buildMeetingTab = function()
	{
		_containingDiv = $('#tabMeetings');
		
		var _meetingMenu = 
			$('<ul/>')
				.append($('<li/>')
					.append($('<a/>')
						.attr('href','#')
						.text('Search')
					)
				)
				.append($('<li/>')
					.append($('<a/>')
						.attr('href','#')
						.text('Start New Meeting')
					)
				)
				.append($('<li/>')
						.append($('<a/>')
							.attr('href','#')
							.text('Edit Meeting Details')
						)
				)
				.append($('<li/>')
						.append($('<a/>')
							.attr('href','#')
							.text('Meeting Types')
						)
				);
		
		_meetingMenu.menu();
		_containingDiv.append(
			$('<table/>')
				.attr({
					'id':'meetingTable',
					'border': 1,
					'width': '100%'
				})
				.css('height','100%')
				.append($('<tr>')
					.append($('<td>')
						.attr({
							id: 'TableMenuSide',
							valign: 'top'
						})
						.append(_meetingMenu)
					)
					.append($('<td>')
						.attr({
							id: 'TableBodySide',
							width: '80%'
						})
					)
				)
		);
	};
	
	$.madminpi.buildPeopleTab = function()
	{
		_containingDiv = $('#tabPeople');
		
		var _peopleMenu = $('<ul/>')
				.append($('<li/>').attr('id','menuPeopleList').append($('<a/>').attr('href','#').text('People List')))
				.append($('<li/>').attr('id','menuNewPerson').append($('<a/>').attr('href','#').text('New Person')))
				.append($('<li/>').attr('id','menuSearch').append($('<a/>').attr('href','#').text('Search')))
				.append($('<li/>').attr('id','menuGroups').append($('<a/>').attr('href','#').text('Groups')))
				.append($('<li/>').attr('id','menuMySettings').append($('<a/>').attr('href','#').text('My Settings')));
		
		_peopleMenu.menu();
		_containingDiv.append(
			$('<table/>')
				.attr({'id':'peopleTable','border': 1,'width': '100%'})
				.css('height','100%')
				.append($('<tr>')
					.append($('<td>')
						.attr({id: 'TableMenuSide',valign: 'top'})
						.append(_peopleMenu))
					.append($('<td>')
						.attr({id: 'TableBodySide',valign: 'top', width: '80%', rowspan: '2'})
						.append($('<div/>')
							.attr({'id':'peopleBody'})
						)
					)
				)
			);
		$('#menuPeopleList').click(function()
		{
			var _carrierList = [];
			var _smsPicker = $('<select>').attr('id','carrierPicker').append($('<option>'));
			
			$.ajax({ 
		  	  	url:"/marc/UserInfoService",
		  	  	data:{"method":"GatherCarrierList"},
				type:'POST',
				dataType:"json",
				success: function(html)
				{
					var _ids = html['CarrierIDs'];
					var _names = html['Carriers'];
					
					for(var i=0; i<_ids.length; i++)
					{
						var _carrierID = _ids[i];
						_carrierList[_carrierID] = _names[i];
						
						_smsPicker.append(
							$('<option>').attr({
								id:_carrierID
							}).text(_names[i])
						);
					}
				},
		  	  	error: function(html)
		  	  	{
			  	  	alert("An error occured while gathering SMS Carrier data." +
							"\nPlease refresh your browser and try again." +
							"\n\nIf problem persists please contact BigHelp Ministries.");
		  	  	}
			});
			
			$.ajax({ 
		  	  	url:"/marc/UserInfoService",
		  	  	data:{"method":"GatherUserList"},
				type:'POST',
				dataType:"json",
				success: function(html)
				{
					var _peopleList = html['UserList'];
					var _mainDiv = $('<div>')
						.attr({
							id:'peopleListCell',
							style:'overflow-y: scroll; max-height: 600px;'
						});
					
					for(var i=0; i<_peopleList.length; i++)
					{
						var _indv = _peopleList[i];
						var _name = _indv['LName'] + ", " + _indv['Pref_Name'];
						
						_mainDiv.append(
							$('<a>').attr({
								'href':'#',
								'id':i,
								'class':'personListLink'
							})
							.text(_name)
						)
						.append("<br>");
					}
					
					$('#peopleTable')
						.append($('<tr>')
							.attr('style','max-height:800px; font-size:12pt;')
							.append($('<td>')
								.attr({valign:'top'})
								.append(_mainDiv)
							)
						);
					
					$('.personListLink').click(function()
					{
						$('#editUserPage').remove();
						
						//Figure out who they clicked
						var _currUser = _peopleList[$(this).attr('id')];
						var _userDiv = $('<div>').attr({'id':'editUserPage'});
						var _name = "";
						var _aliasList = [];
						
						$.ajax({ 
					  	  	url:"/marc/UserInfoService",
					  	  	data:{
					  	  		"method":"GatherKnownAliases",
					  	  		"UserId":_currUser['UserId']
					  	  	},
							type:'POST',
							dataType:"json",
							success: function(html)
							{
								var _rows = html['Rows'];
								var _types = html['Types'];
								var _ids = html['Aliases'];
								var _active = html['Active'];
								
								for(var i=0; i<_ids.length; i++)
								{
									var _currRow = _rows[i];
									var _currAlias = _ids[i];
									var _currType = _types[i];
									var _currActive = _active[i];
									
									_aliasList.push({"Alias":_currAlias, "Type":_types[i], "Active":_currActive});
								}
							},
					  	  	error: function(html)
					  	  	{
						  	  	alert("An error occured while gathering SMS Carrier data." +
										"\nPlease refresh your browser and try again." +
										"\n\nIf problem persists please contact BigHelp Ministries.");
					  	  	}
						});
						
						//Format the person's name
						if(_currUser['FName'] == _currUser['Pref_Name'])
							_name = _currUser['FName'] + " " + _currUser['LName'];
						else
							_name = _currUser['FName'] + " \"" + _currUser['Pref_Name'] + "\" " + _currUser['LName'];
						
						//Create the table and append it to the div
						_userDiv.append($('<table>')
							.attr({
								width:'100%',
								border:'2'
							})
							.append($('<tr>')
								.append($('<td>')
									.attr({
										width:'20%',
										rowspan:'4',
										align: 'center'
									})
									.append($('<img>') //TODO make clickable with pop-up box to change address of pic
										.attr({
											src:_currUser['Picture'],
											height:'150px'
										})
									)
								)
								.append($('<td>')
									.append($('<b>').append("Name: "))
									.append(_name)
								)
							)
							.append($('<tr>')
								.append($('<td>')
									.append($('<b>').append("UserID: "))
									.append(_currUser['UserId'])
								)
							)
							.append($('<tr>')
								.append($('<td>')
									.append($('<b>').append("Access Level: "))
									.append(_currUser['Access_Level'])
								)
							)
							.append($('<tr>')
									.append($('<td>')
										.append($('<b>').append("Reports to: "))
										.append(_currUser['ReportsTo'])
									)
								)
						) //Then create the accordions too
						.append(
							$('<div>')
								.attr('id','userAccordion')
								
								//Personal Info Accordion
								.append($('<h3>').text("Personal Info"))
								.append(
									$('<p>').append($('<table>')
										.attr({
											width:'100%',
											border:'0'
										})
										
										//Legal/Preferred Name
										.append($('<tr>')
											.append($('<td>').append("Legal Name: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text'})
													.val(_currUser['FName'])
												)
												.append("&nbsp;&nbsp;")
												.append($('<input>')
													.attr({'type':'text', 'size':'2'})
													.val(_currUser['MInitial'])
												)
												.append("&nbsp;&nbsp;")
												.append($('<input>')
													.attr({'type':'text'})
													.val(_currUser['LName'])
												)
											)
											.append($('<td>').append($('<button>').attr({'class':'updatePersonalInfoButton'}).text("Update")))
										)
										.append($('<tr>')
											.append($('<td>').append("Preferred Name: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'10'})
													.val(_currUser['Pref_Name'])
												)
												.append("<br><br>")
											)
										)
										
										//Address
										.append($('<tr>')
											.append($('<td>').append("Address: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text'})
													.val(_currUser['Address'])
												)
												.append($('<br>'))
												.append($('<input>')
													.attr({'type':'text', 'size':'20'})
													.val(_currUser['City'])
												)
												.append(", Tx &nbsp;&nbsp;")
												.append($('<input>')
													.attr({'type':'text', 'size':'5'})
													.val(_currUser['Zip'])
												)
												.append("<br><br>")
											)
										)
										
										//DoB
										.append($('<tr>')
											.append($('<td>').append("Date of Birth: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'10'})
													.val(_currUser['DOB'])
												)
											)
										)
										
										//Gender
										.append($('<tr>')
											.append($('<td>').append("Gender: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'1'})
													.val(_currUser['Gender'])
												)
												.append("<br><br>")
											)
										)
										
										//Phone/Carrier
										.append($('<tr>')
											.append($('<td>').append("Phone/Carrier: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'12'})
													.val(_currUser['Phone']))
												.append("&nbsp;&nbsp")
												.append(_smsPicker.prop('selectedIndex',_currUser['Carrier']))
											)
										)
										
										//Email
										.append($('<tr>')
											.append($('<td>').append("Email: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'30'})
													.val(_currUser['Email']))
											)
										)
										
										//Shirt Size
										.append($('<tr>')
											.append($('<td>').append("Shirt Size (adult): "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'2'})
													.val(_currUser['Shirt']))
											)
											.append("<br><br>")
										)
										
										//School/grade
										.append($('<tr>')
											.append($('<td>').append("School/Grade: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'30'})
													.val(_currUser['School'])
												)
												.append("&nbsp;&nbsp;&nbsp;")
												.append($('<input>')
													.attr({'type':'text', 'size':'2'})
													.val(_currUser['Grade'])
												)
												.append("<br><br>")
											)
										)
										
										//Sacraments/Confirmation
										.append($('<tr>')
											.append($('<td>').append("Highest Sacrament / <br>Confirmation Level: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'10'})
													.val(_currUser['Highest_Sacrament'])
												)
												.append("&nbsp;&nbsp;&nbsp;")
												.append($('<input>')
													.attr({'type':'text', 'size':'2'})
													.val(_currUser['Confirmation'])
												)
												.append("<br><br>")
											)
										)
										
										//Insurance Info
										.append($('<tr>')
											.append($('<td>').append("Insurance Company/No.: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'30'})
													.val(_currUser['InsuranceCo']))
												.append("<br>")
												.append($('<input>')
													.attr({'type':'text', 'size':'30'})
													.val(_currUser['InsuranceNum']))
												.append("<br><br>")
											)
										)
										
										//Medications
										.append($('<tr>')
											.append($('<td>').append("Medications:<br>Allergies:<br><br>Medical Issues: <br>"))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'20'})
													.val(_currUser['Medications']))
												.append("<br>")
												.append($('<input>')
													.attr({'type':'text', 'size':'20'})
													.val(_currUser['Allergies']))
												.append("<br>")
												.append($('<textarea>')
													.attr({style:'height: 50px; width: 300px;', rows:'3', columns:'8', valign: 'top'})
													.val(_currUser['MedicalIssues']))
											)
										)
										
										//Permission to Treat
										.append($('<tr>')
											.append($('<td>').append("Permission to Treat: "))
											.append($('<td>')
												.append($('<select>')
													.attr({'id':'permissionPicker'})
													.append($('<option>').attr({id:'0'}).text("No"))
													.append($('<option>').attr({id:'1'}).text("Yes"))
													.prop('selectedIndex',_currUser['PermissionToTreat'])
												)
												.append("<br><br>")
											)
										)
										
										//Emergency Contact/Relation
										.append($('<tr>')
											.append($('<td>').append("Emg. Contact/Number:<br>Relation: "))
											.append($('<td>')
												.append($('<input>')
													.attr({'type':'text', 'size':'20'})
													.val(_currUser['EmgContact']))
												.append("&nbsp;&nbsp;&nbsp;")
												.append($('<input>')
													.attr({'type':'text', 'size':'20'})
													.val(_currUser['EmgNumber']))
												.append("<br>")
												.append($('<input>')
													.attr({'type':'text', 'size':'20'})
													.val(_currUser['EmgRelation']))
											)
											.append($('<td>').append($('<button>').attr({'class':'updatePersonalInfoButton'}).text("Update")))
										)
									)
								)
								
								//Statistics accordion
								.append($('<h3>').text("Statistics"))
								.append(
									$('<p>').append(
										$('<table>').attr({
											width:'100%'
										})
										.append(
											"Statistics stuff"
											/* 
											 * Attendance percentage: 
											 * Alias usage: 
											 * Information Compliance:
											 * Average sign-in time:  
											 * */
										)
									)
								)
								
								//Aliases accordion
								.append($('<h3>').text("Aliases"))
								.append(
									$('<p>').append($('<table>')
										.attr({width:'100%', border:'1'})
										
										.append($('<tr>')
											.append($('<td>')
												.append("Alias Stuff")
											)
										)
									)
								)
								
								//Groups accordion
								.append(
									$('<h3>').text("Group Membersip")
								)
								.append(
									$('<p>').append($('<table>')
										.attr({width:'100%', border:'1'})
										
										.append($('<tr>')
											.append($('<td>')
												.append("Group Stuff")
											)
										)
									)
								)
							);
						
						$('#peopleBody').append(_userDiv);
						$('#userAccordion').accordion({collapsible: true, active: false});
						
						$('.updatePersonalInfoButton').click(function(){
							//Send updated data to MySQL
							alert("This is not active yet, but would send the data you updated back to the Database ;).");
						});
						$('.updateAliasButton').click(function(){
							//Send updated data to MySQL
							alert("This is not active yet, but would send the data you updated back to the Database ;).");
						});
						$('.updateGroupsButton').click(function(){
							//Send updated data to MySQL
							alert("This is not active yet, but would send the data you updated back to the Database ;).");
						});
					});
				},
				error: function(html){
					alert("An error occured while gathering Report data." +
							"\nPlease refresh your browser and try again." +
							"\n\nIf problem persists please contact BigHelp Ministries.");
				}
			}); //Closes AJAX
		});
		$('#menuNewPerson').click(function()
		{
			$('#globalSettings').data('newPersonTargetDiv','personBody');
			$('head').append($('<script>').attr('src','js/newPersonForm.js'));
		});
		$('#menuSearch').click(function()
		{
			alert("Clicked Search!");
		});
		$('#menuGroups').click(function()
		{
			alert("Clicked Groups!");
		});
		$('#menuMySettings').click(function()
		{
			alert("Clicked My Settings!");
		});
		
		$('#menuPeopleList').click();
	};
	
	$.madminpi.buildReportsTab = function()
	{
		_containingDiv = $('#tabReports');
		
		var _reportsMenu = 
				$('<ul/>')
					.attr('id','reportsMenu')
					.append($('<li/>')
						.attr('id','menuAttendance')
						.append($('<a/>')
							.attr('href','#')
							.text('Attendance')
						)
					)
					.append($('<li/>')
						.attr('id','menuMembership')
						.append($('<a/>')
							.attr('href','#')
							.text('Membership')
						)
					)
					.append($('<li/>')
						.attr('id','menuAliasUsage')
						.append($('<a/>')
							.attr('href','#')
							.text('New Student')
						)
				);
		
		_reportsMenu.menu();
		_containingDiv.append(
			$('<table/>')
				.attr({
					'id':'reportsTable',
					'border': 1,
					'width': '100%'
				})
				.css('height','100%')
				.append($('<tr>')
					.append($('<td>')
						.attr({
							id: 'TableMenuSide',
							valign: 'top'
						})
						.append(_reportsMenu)
					)
					.append($('<td>')
						.attr({
							id: 'TableBodySide',
							width: '80%'
						})
						.append($('<div/>').attr('id','reportsBody'))
					)
				)
		);
		
		$('#menuAttendance').click(function()
		{
			$.ajax({ 
		  	  	url:"/marc/ReportDataService",
		  	  	data:{"ReportType":"attendanceBasic"},
				type:'POST',
				dataType:"json",
				success: function(html){
					makeGraph(html['Meetings']);
				},
				error: function(html){
					alert("An error occured while gathering Report data." +
							"\nPlease refresh your browser and try again." +
							"\n\nIf problem persists please contact BigHelp Ministries.");
				}
			}); //Closes AJAX
			
	        function makeGraph(mtgData)
	        {
	        	var _categoryArray = [];
	            var _data = [];
	            var length = mtgData.length;
	            
	            for (var i = 0; i < length; i++) {
	            	_categoryArray[i] = mtgData[i]['Start Date'];
	            	_data[i] = mtgData[i]['Attendees'];
	            };
	    
	            var chart = new Highcharts.Chart({
            		chart: {
                        renderTo: 'reportsBody',
                        type: 'line',
                        marginRight: 130,
                        marginBottom: 25
                    },
                    exporting: {
                    	enabled: false
                    },
                    credits: {
                    	enabled: false
                    },
                    title: {
                        text: 'LifeNight Meeting Attendance',
                        x: -20 //center
                    },
                    subtitle: {
                        text: 'Last 6 LifeNights',
                        x: -20
                    },
                    xAxis: {
                        categories: _categoryArray
                    },
                    yAxis: {
                        title: {
                            text: 'Students'
                        },
                        tickInterval: 5,
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#808080'
                        }]
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -10,
                        y: 50,
                        borderWidth: 0
                    },
                    series: [{
                    	name: 'Attendance',
                    	data: _data
                    }]
	            });
	        };
		});
		
		$('#menuMembership').click(function()
				{
			$.ajax({ 
		  	  	url:"/marc/ReportDataService",
		  	  	data:{"ReportType":"membership"},
				type:'POST',
				dataType:"json",
				success: function(html){
					makeGraph(html['Meetings']);
				},
				error: function(html){
					alert("An error occured while gathering Report data." +
							"\nPlease refresh your browser and try again." +
							"\n\nIf problem persists please contact BigHelp Ministries.");
				}
			}); //Closes AJAX
			
	        function makeGraph(mtgData)
	        {
	        	var _categoryArray = [];
	            var _data = [];
	            var length = mtgData.length;
	            
	            for (var i = 0; i < length; i++) {
	            	_categoryArray[i] = mtgData[i]['Start Date'];
	            	_data[i] = mtgData[i]['Attendees'];
	            };
	    
	            var chart = new Highcharts.Chart({
            		chart: {
                        renderTo: 'reportsBody',
                        type: 'line',
                        marginRight: 130,
                        marginBottom: 25
                    },
                    exporting: {
                    	enabled: false
                    },
                    credits: {
                    	enabled: false
                    },
                    title: {
                        text: 'LifeNight Meeting Attendance',
                        x: -20 //center
                    },
                    subtitle: {
                        text: 'Last 6 LifeNights',
                        x: -20
                    },
                    xAxis: {
                        categories: _categoryArray
                    },
                    yAxis: {
                        title: {
                            text: 'Students'
                        },
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#808080'
                        }]
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -10,
                        y: 50,
                        borderWidth: 0
                    },
                    series: [{
                    	name: 'Attendance',
                    	data: _data
                    }]
	            });
	        };
		});
		$('#menuAliasUsage').click(function()
				{
			$.ajax({ 
		  	  	url:"/marc/ReportDataService",
		  	  	data:{"ReportType":"aliasUsage"},
				type:'POST',
				dataType:"json",
				success: function(html){
					makeGraph(html['Meetings']);
				},
				error: function(html){
					alert("An error occured while gathering Report data." +
							"\nPlease refresh your browser and try again." +
							"\n\nIf problem persists please contact BigHelp Ministries.");
				}
			}); //Closes AJAX
			
	        function makeGraph(mtgData)
	        {
	            var _data = [[], []];
	            var length = reportData.length;
	            
	            for (var i = 0; i < length; i++) {
	            	_data[i][0] = reportData[i]['Alias Type'];
	            	_data[i][1] = reportData[i]['Usage'];
	            };
	    
	            var chart = new Highcharts.Chart({
            		chart: {
                        renderTo: 'reportsBody',
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false
                    },
                    exporting: {
                    	enabled: false
                    },
                    credits: {
                    	enabled: false
                    },
                    title: {
                        text: 'Overall Alias Usage'
                    },
                    tooltip: {
                	    pointFormat: '{series.name}: <b>{point.percentage}%</b>',
                    	percentageDecimals: 1
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,
                                color: '#000000',
                                connectorColor: '#000000',
                                formatter: function() {
                                    return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
                                }
                            }
                        }
                    },
                    series: [{
                        type: 'pie',
                        name: 'Alias Usage',
                        data: _data
                    }]
	            });
	        };
		});
	};
})(jQuery);